package com.enqualcomm.kids.mvp.location;

import com.android.volley.socket.SocketStack;
import com.enqualcomm.kids.network.socket.response.LocationActiveResult;
import com.enqualcomm.kids.network.socket.response.LocationResult;
import com.google.gson.Gson;

import java.net.Socket;

import common.utils.GsonFactory;
import common.utils.MyLogger;

public class ReceiveRunnable implements Runnable {
    private Socket socket;
    private LocationCallBack callBack;
    private Gson gson;

    public ReceiveRunnable(Socket socket, LocationCallBack callBack) {
        this.socket = socket;
        this.callBack = callBack;
    }

    @Override
    public void run() {
        gson = GsonFactory.newInstance();
        g:
        while (callBack.getTimeout() > 0) {
            String data = receiveData();
            if (data != null) {
                LocationActiveResult locationActiveResult = gson.fromJson(data, LocationActiveResult.class);
                if (locationActiveResult.code == 0) {
                    switch (locationActiveResult.result.state) {
                        case 0://长连接定位成功
                        case 1://短连接定位成功
                            callBack(200, locationActiveResult.result.content, true);
                            break g;
                        case 2://手表收到指令
                            callBack(101, locationActiveResult.result.content, false);
                            break;
                        case 3://短信指令关机
                        case 4://手动关机
                        case 5://低电关机
                            callBack(102, null, true);
                            break g;
                    }
                }
            } else {//send线程最终会关闭socket，导致这边抛出异常，result=null
                if (callBack.closeSocketBySelf) {//超时关闭
                    callBack.onReceiveLocation(2, null);
                } else {
                    callBack.onReceiveLocation(1, null);//网络错误
                    callBack.invalidate();
                }
                break;
            }
        }
    }

    private void callBack(int state, LocationResult.Data content, boolean destroy) {
        if (destroy) {
            callBack.invalidate();
        }
        callBack.onReceiveLocation(state, content);
    }


    /**
     * 接收服务器传回的数据
     *
     * @return 接收到的数据，null表示网络错误
     */
    private String receiveData() {
        String result = null;
        try {
            byte[] receive = SocketStack.receive(socket);
            result = new String(receive);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        MyLogger.jLog().i(result);
//        添加处理返回值不是完整的json
        if (result != null && !result.startsWith("{")) {
            result = "{" + result;
        }
        if (result != null && !result.endsWith("}")) {
            result = result + "}";
        }
        return result;
    }

}